package com.cloud.point.javase;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 反射的使用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-07-04 17:20
 */
@Slf4j
public class TestReflect {

    public static void main(String[] args) throws Exception {
        User user1 = new User();
        Class<? extends User> clazz1 = user1.getClass();
        log.info("反射实例对象1:{}", clazz1);
        Class<User> clazz2 = User.class;
        User user = clazz2.newInstance();
        log.info("反射实例对象2:{}", clazz2);
        Class<?> clazz3 = Class.forName("com.cloud.point.javase.User");
        log.info("反射实例对象3:{}", clazz3);

        /**
         * 调用运行时类中的指定的属性
         */
        Field name = clazz2.getDeclaredField("name");
        name.setAccessible(true);
        name.set(user, "aaa");
        String o = (String) name.get(user);
        log.info("反射方法属性{}", o);

        /**
         * 调用运行时类中的指定的方法
         */
        Method nameMethod = clazz2.getMethod("getName");
        Object invoke = nameMethod.invoke(user);
        log.info("方法反射调用:{}", invoke);
        Method nameMethod2 = clazz2.getMethod("get", String.class, Integer.class);
        Object invoke2 = nameMethod2.invoke(user, "a", 1);
        log.info("方法反射调用2:{}", invoke2);

        /**
         * 父类属性
         */
        Class<?> superclass = clazz2.getSuperclass();
        log.info("反射实例对象父类{}", superclass);
        Type genericSuperclass = clazz2.getGenericSuperclass();
        log.info("反射实例对象带泛型父类{}", genericSuperclass);
        ParameterizedType paramType = (ParameterizedType) genericSuperclass;
        log.info("反射实例对象带泛型父类的泛型参数{}", paramType);
        Type[] typeArguments = paramType.getActualTypeArguments();
        log.info("反射实例对象带泛型父类的泛型参数{}", Arrays.asList(typeArguments));

    }

}

@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
class User extends Human<String> {

    private String name;

    public String get(String str, Integer num) {
        return str + "::" + num;
    }

}

class Human<T> {

    public T t;

}
